// pages/cart/index.js
// 获取应用实例
const app = getApp()
const { shopInfo } = require('../../config/index')

import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
const computedBehavior = require('miniprogram-computed').behavior

Page({
    behaviors: [computedBehavior],

    /**
     * 页面的初始数据
     */
    data: {
        viewUrl: app.globalData.viewUrl,
        cartList: [],
        loading: false,
        shopInfo,
        sendMode: "0",
        payMode: "1",
        timeMode: "1",
        minDate: new Date().getTime() + 30 * 60000,
        sendTime: "",
        addressInfo: null,

        remark: "",
        showRemarkInput: false,
        fastRemark: ["不要辣", "饮料不加冰", "不需要餐具"],

        timePickerVisible: false
    },
    computed: {
        totalAmount(data) {
            let res = 0
            if (data.cartList && data.cartList.length) {
                for (let i = 0; i < data.cartList.length; i++) {
                    const ele = data.cartList[i];
                    res += ((ele.price || 0) * (ele.number || 0))
                }
            }
            return res * 100
        },
        totalOriginalAmout(data) {
            let res = 0
            if (data.cartList && data.cartList.length) {
                for (let i = 0; i < data.cartList.length; i++) {
                    const ele = data.cartList[i];
                    res += ((ele.originalPrice || ele.price || 0) * (ele.number || 0))
                }
            }
            return res.toFixed(2)
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.getCartList()
        this.getAddressInfoById()
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        this.getCartList()
    },

    /**
     * 获取购物车数据
     */
    async getCartList() {
        const { data } = await app.requestAll({
            url: 'cart/selectListByUser',
            alert: false
        })
        this.setData({
            cartList: data || []
        })
        wx.stopPullDownRefresh()
    },
    /**
     * 获取地址信息
     */
    async getAddressInfoById() {
        const { data, code, msg } = await app.requestAll({
            url: 'address/selectDefaultByUser',
            alert: false
        })
        if (code !== 200) return wx.showToast({
            title: msg,
            icon: 'error'
        })
        this.setData({
            addressInfo: data
        })
    },

    /**
     * 更新购物车数据
     * 增删改
     * @param {*} e 
     */
    async updateCart(e) {
        const dataset = Object.keys(e.target.dataset).length ? e.target.dataset : e.currentTarget.dataset
        this.setData({
            ['cartList[' + dataset.index + '].number']: e.detail
        })
        const { data } = await app.requestAll({
            url: 'cart/updateCartByUser',
            method: "POST",
            params: {
                id: dataset.row.id,
                productId: dataset.row.productId,
                number: e.detail,
            },
            alert: false
        })
    },
    async removeProduct(e) {
        Dialog.confirm({
            message: '确定要将该商品移出购物车吗？',
        }).then(async () => {
            const dataset = Object.keys(e.target.dataset).length ? e.target.dataset : e.currentTarget.dataset
            await app.requestAll({
                url: 'cart/removeFromCart',
                method: "POST",
                params: {
                    id: dataset.row.id,
                }
            })
            this.getCartList()
        })
    },
    /**
     * 提交订单
     * @param {*} e 
     */
    onSubmit(e) {
        this.setData({ aloading: true })
        Dialog.confirm({
            message: '确定商品选择无误并要提交订单吗？',
        }).then(async () => {
            const { data, code } = await app.requestAll({
                url: 'order/addByUser',
                method: "POST",
                params: {
                    paymode: this.data.payMode,
                    sendmode: this.data.sendMode,
                    remark: this.data.remark,
                    userAddress: this.data.addressInfo.id,
                    userMobile: this.data.addressInfo.mobile
                },
                alert: false
            })
            this.setData({ aloading: false })
            if (code !== 300) return wx.showToast({ title: '订单提交失败', icon: 'error' });
            wx.showToast({ title: '订单提交成功！', icon: 'success' });
            this.getCartList()
            wx.reLaunch({
                url: '/pages/order/index',
            })
        });
    },


    sendModeChange(e) {
        this.setData({
            sendMode: e.detail
        })
    },
    timeModeChange(e) {
        this.setData({
            timeMode: e.detail
        })
    },
    payModeChange(e) {
        this.setData({
            payMode: e.detail
        })
    },
    showRemarkInput() {
        this.setData({ showRemarkInput: !this.data.showRemarkInput })
    },
    showTimePicker() {
        this.setData({ timePickerVisible: !this.data.timePickerVisible })
    },
    timeChange(e) {
        console.log(e);
        this.setData({ sendTime: e.detail.value, timePickerVisible: e.detail.show })
    },
    remarkChange(e) {
        this.setData({ remark: e.detail.value })
    },
    addFastRemark(e) {
        const dataset = Object.keys(e.target.dataset).length ? e.target.dataset : e.currentTarget.dataset
        this.setData({
            remark: this.data.remark ? this.data.remark + ',' + dataset.text : dataset.text
        })
    },
    toAddressPage() {
        wx.navigateTo({
            url: '/pages/address/index',
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})